/**
 * 42. 接雨水
 * https://leetcode-cn.com/problems/trapping-rain-water/
 */

/**
 * @param {number[]} height
 * @return {number}
 */
function trap(height) {
  const maxesLeft = new Array(height.length);
  const maxesRight = new Array(height.length);
  let max = 0;
  for (let i = 0; i < height.length; i += 1) {
    maxesLeft[i] = max;
    max = Math.max(max, height[i]);
  }
  max = 0;
  for (let i = height.length - 1; i >= 0; i -= 1) {
    maxesRight[i] = max;
    max = Math.max(max, height[i]);
  }
  let area = 0;
  for (let i = 0; i < height.length; i += 1) {
    area += Math.max(Math.min(maxesLeft[i], maxesRight[i]) - height[i], 0);
  }
  return area;
}

console.log(trap([0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1]) === 6);
console.log(trap([4, 2, 0, 3, 2, 5]) === 9);
console.log(trap([1]) === 0);
